package com.chuangmei.com.arindoorlocationsystem.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Looper;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;

import com.chuangmei.com.arindoorlocationsystem.R;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2017/2/22 0022.
 */
public class CommonUtils {

    /**
     * 检查系统目录是否存在
     */
    public static void CheckSystemDir() {
        FileUtils.delete(Constant.dir_temp);
        FileUtils.CheckDir(Constant.root_dir);
        FileUtils.CheckDir(Constant.dir_video);
        FileUtils.CheckDir(Constant.dir_data);
        FileUtils.CheckDir(Constant.dir_cache);
        FileUtils.CheckDir(Constant.dir_error);
    }

    public static View findParentView(View view, int targetId) {
        if (view.getId() == targetId) {
            return view;
        }
        View parent = (View) view.getParent();
        if (parent == null) {
            return null;
        }
        return findParentView(parent, targetId);
    }

    /**
     * */
    public static String RemoveNull(String value) {
        if (value == null) {
            return "";
        }
        return value;
    }

    /**
     * 判断当前是否在主线程
     *
     * @return
     */
    public static boolean isInMainThread() {
        Looper myLooper = Looper.myLooper();
        Looper mainLooper = Looper.getMainLooper();
        boolean b = myLooper == mainLooper;
        LogUtils.debug("myLooper=" + myLooper + "--mainLooper=" + mainLooper + "--isEqual:" + b);
        return b;
    }


    public static String getUUID() {
        return java.util.UUID.randomUUID().toString();
    }


    public static HashMap<String, Object> getAutoLoginMap(Context context) {
        SharedPreferences preferences = context.getApplicationContext().getSharedPreferences(
                "fjaslkjfiosdiewi", Context.MODE_MULTI_PROCESS);
        if (preferences != null && preferences.getAll().size() > 0) {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("user_login_time", preferences.getString("user_login_time", null));
            map.put("user_name", preferences.getString("user_name", null));
            map.put("user_password", preferences.getString("user_password", null));
            map.put("server_canton", preferences.getString("server_canton", null));
            return map;
        } else {
            return null;
        }
    }

    public static void setAutoLoginClear(Context context) {
        SharedPreferences preferences = context.getApplicationContext().getSharedPreferences(
                "fjaslkjfiosdiewi", Context.MODE_MULTI_PROCESS);
        preferences.edit().clear();
    }

    /**
     * 获取文件所属文件夹
     *
     * @param pathandname
     * @return
     */
    public static String getFileDir(String pathandname) {
        File f = new File(pathandname);
        return f.getParent();
    }

    /*
    * 从网址中获取文件名（不带后缀）
    * */
    public static String getFileName(String pathandname) {
        int start = pathandname.lastIndexOf("/");
        int end = pathandname.lastIndexOf(".");
        if (start != -1 && end != -1) {
            return pathandname.substring(start + 1, end);
        }
        return null;
    }

    /*
    * 从网址中获取文件全名（带后缀）
    * */
    public static String getFileFullName(String pathandname) {
        int start = pathandname.lastIndexOf("/");
        int end = pathandname.lastIndexOf("?");
        if (start != -1) {
            if (end == -1) {
                return pathandname.substring(start + 1);
            } else if (end > start) {
                return pathandname.substring(start + 1, end);
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    /*
    * 从网址中获取文件后缀
    * */
    public static String getFileExt(String pathandname) {
        if (TextUtils.isEmpty(pathandname)) {
            return null;
        }
        String ext = null;
        int start = pathandname.lastIndexOf(".");
        int end = pathandname.lastIndexOf("?");
        if (start != -1) {
            if (end == -1) {
                ext = pathandname.substring(start + 1);
            } else if (end > start) {
                ext = pathandname.substring(start + 1, end);
            }
        }
        if (!TextUtils.isEmpty(ext)) {
            ext = ext.toLowerCase();
        }
        return ext;
    }

    /**
     * 判断service是否在后台运行
     *
     * @param mContext
     * @param mClass
     * @return
     */
    public static boolean isServiceRunning(Context mContext, Class<?> mClass) {
        return isServiceRunning(mContext, mClass.getName());
    }

    public static boolean isServiceRunning(Context mContext, String seachName) {
        boolean isWork = false;
        seachName = seachName.toLowerCase();
        ActivityManager myAM = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = myAM.getRunningServices(Integer.MAX_VALUE);
        if (myList.size() <= 0) {
            return false;
        }
        for (int i = 0; i < myList.size(); i++) {
            String serviceName = myList.get(i).service.getClassName().toLowerCase();
            if (serviceName.equals(seachName)) {
                isWork = true;
                break;
            }
        }
        LogUtils.debug(seachName + " isRunning: " + isWork);
        return isWork;
    }

    /**
     * 关闭服务
     */
    public static boolean stopService(Context mContext, Class<?> mClass) {
        if (isServiceRunning(mContext, mClass)) {
            Intent mIntent = new Intent(mContext, mClass);
            if (mContext.stopService(mIntent)) {
                LogUtils.debug("服务关闭=====" + true);
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }

    /**
     * 获取屏幕宽度
     *
     * @param context
     * @return
     */
    public static int getWindowWidth(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        return width;
    }

    /**
     * 获取屏幕高度
     *
     * @param context
     * @return
     */
    public static int getWindowHeight(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        int height = wm.getDefaultDisplay().getHeight();
        return height;
    }

    /**
     * 获取真实屏幕尺寸，单位寸
     *
     * @param activity
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    public static double getScreenSizeOfDevice2(Activity activity) {
        Point point = new Point();
        activity.getWindowManager().getDefaultDisplay().getRealSize(point);
        DisplayMetrics dm = activity.getResources().getDisplayMetrics();
        double x = Math.pow(point.x / dm.xdpi, 2);
        double y = Math.pow(point.y / dm.ydpi, 2);
        double screenInches = Math.pow(Math.pow(x, 2) + Math.pow(y, 2), 0.5);
        return screenInches;
    }


    public static void requestView(View view) {
        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) view.getLayoutParams();
        layoutParams.setMargins(0, 0, ((FrameLayout) view.getParent()).getWidth() / 20, 0);
        view.setLayoutParams(layoutParams);
        view.requestLayout();
    }


    public String getRandomLayerUUID(Context context, String drawDir) {


        return null;
    }


    /*
    * 获取Drawable的背景色
    * */
    public static int getDrawableColor(Drawable drawable) {
        if (drawable instanceof ColorDrawable) {
            ColorDrawable colorDrawable = (ColorDrawable) drawable;
            return colorDrawable.getColor();
        } else if (drawable instanceof BitmapDrawable) {
            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
            int pixelColor = bitmap.getPixel(bitmap.getWidth() / 2, bitmap.getHeight() / 2);
            return Color.rgb(Color.red(pixelColor), Color.green(pixelColor), Color.blue(pixelColor));
        } else {
            return R.color.black;
        }
    }

    public static int getViewBackColor(View v) {
        if (v == null) {
            return 0;
        } else {
            Drawable drawable = v.getBackground();
            return getDrawableColor(drawable);
        }
    }

    /**
     * 去除字符串中的特殊符号
     *
     * @param text
     * @return
     */
    public static String removeSpecial(String text) {
        String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？'\",.]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(text);
        return m.replaceAll("").trim();
    }

    /**
     * 获取当前长时间
     *
     * @return
     */
    public static long getLongTime() {
        return System.currentTimeMillis() / 1000;
    }

    /**
     * 存入时编码
     *
     * @param value
     * @return
     */
    public static String encode(String value) {
        return value;
    }

    /**
     * 读取时解码
     *
     * @param value
     * @return
     */
    public static String decode(String value) {
        return value;
    }


    /**
     * 获取屏幕尺寸大小（对角线英寸长度）
     *
     * @param context
     * @param widthpx
     * @param heightpx
     * @return
     */
    public static double getScreenSize(Context context, int widthpx, int heightpx) {
        float widthIN = widthpx / context.getResources().getDisplayMetrics().xdpi;
        float heightIN = heightpx / context.getResources().getDisplayMetrics().ydpi;
        double value = Math.pow(Math.pow(widthIN, 2f) + Math.pow(heightIN, 2f), 0.5f);
        return value;
    }
}
